package com.gdou.controller;

import com.gdou.commons.Result;
import com.gdou.commons.UploadBean;
import com.gdou.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    private UploadBean uploadBean;

    @Autowired
    private AccountService accountService;

    @RequestMapping("/uploadFile")
    public Result uploadFile(MultipartFile headImg, HttpSession session) throws IOException {
        if (headImg.isEmpty()){
            return new Result(-1,"上传的文件不能为空");
        }
        /*获取文件后缀名*/
        /*文件名*/
        String originalFilename = headImg.getOriginalFilename();
        /*后缀名*/
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
        /*随机字符串 文件名*/
        String uuid = UUID.randomUUID().toString();
        /*保存文件夹地址*/
        String saveUrl = uploadBean.getBaseUrl();
        File file = new File(saveUrl);
        if (!file.exists()){
            file.mkdirs();//创建文件夹
        }
        /*文件保存的 最终完整地址*/
        File finalFile = new File(saveUrl + "/" + uuid + ext);
        /*写文件  保存*/
        headImg.transferTo(finalFile);
        /*修改数据库中的 头像数据*/
        Result result = accountService.modifyAccountImgUrl(session,uuid+ext);
        if (result.getCode()==200){
            result.setData(uuid+ext);//响应新的 文件名
        }
        return result;
    }
}
